<?php

namespace app\admin\controller;

use app\common\ApiBase;
use app\common\ApiStatus;
use app\common\OsType;
use app\model\SystemAdmin;
use app\traits\Curd;
use support\Redis;
use support\Response;
use think\db\exception\PDOException;
use think\facade\Db;

class Category extends ApiBase
{
    use Curd;

    public function beforeAction()
    {
        if (empty(request()->admin_uid)) return $this->apiFailed('请先登录', ApiStatus::API_NEED_LOGIN->value);
        parent::beforeAction();
        $this->model      = new \app\model\Category();
        $this->order_sort = 'sort asc';
        $this->params     = $this->buildTableParams(-1);
    }

    public function lists(): Response
    {
        list($page, $limit, $where) = $this->params;
        $where[] = ['is_del', '=', 0];
        $count   = $this->model->where($where)->count();
        $list    = $this->model->where($where)
            ->page($page, $limit)
            ->order($this->order_sort)
            ->select();
        $notes   = $this->model->notes ?? [];
        //管理员列表
        $adminUserListRedis = Redis::get('admin:list:admin_user');
        if (!$adminUserListRedis) {
            $adminUserList = SystemAdmin::getColumn([], 'username', 'id desc', 'id');
            Redis::set('admin:list:admin_user', json_encode($adminUserList), 'EX', 60 * 60 * 3, 1);
        } else {
            $adminUserList = json_decode($adminUserListRedis, true);
        }
        $notes['admin_user'] = $adminUserList;
        $notes['os_type']    = OsType::values();

        return $this->apiSuccess(compact('count', 'list', 'notes'));
    }

    public function add(): Response
    {
        $errorMessage = '';
        $post         = request()->post();
        if (isset($post['id'])) unset($post['id']);
        if (isset($post['uuid'])) unset($post['uuid']);
        if (isset($post['admin_os_type'])) unset($post['admin_os_type']);

        try {
            $post['c_time']    = date('Y-m-d H:i:s');
            $post['admin_uid'] = \request()->admin_uid ?? 0;
            $id                = $this->model->insertGetId($post);
            $data['sort']      = $id * 66;
            $save              = $this->model->where('id', $id)->update($data);
        } catch (\Exception $e) {
            $errorMessage = $e->getMessage();
            $save         = false;
        }
        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => $save ? '操作成功' : '操作失败:' . $errorMessage, 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }

    public function edit(): Response
    {
        return $this->apiFailed('不支持操作');
    }

    public function delete(): Response
    {
        $errorMessage = '';
        $post         = \request()->post();
        $ids          = $post['ids'] ?? [0];
        if (is_string($ids)) $ids = json_decode($ids, true);
        $row = $this->model->whereIn('id', $ids)->select();
        if ($row->isEmpty()) return json(['code' => ApiStatus::API_ERROR->value, 'msg' => '删除数据不存在', 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
        if (isset($post['id'])) unset($post['id']);

        // 启动事务
        Db::startTrans();
        try {
            $data = [
                'u_time' => myDate(),
                'is_del' => 1,
            ];
            Db::table('category')->whereIn('id', $ids)->update($data);
            $bannerList = \app\model\Banner::getAllList([['is_del', '=', 0]], 'id,category_ids');
            foreach ($bannerList as $value) {
                $categoryIdArr = explode(',', $value['category_ids']);
                foreach ($categoryIdArr as $idkey => $idvalue) {
                    if (in_array($idvalue, $ids)) {
                        unset($categoryIdArr[$idkey]);
                    }
                }
                $categoryIds = implode(',', $categoryIdArr);
                if ($categoryIds != $value['category_ids']) {
                    $update = [
                        'id'           => $value['id'],
                        'u_time'       => myDate(),
                        'category_ids' => $categoryIds,
                    ];
                    Db::table('banner')->whereIn('id', $value['id'])->update($update);
                }
            }

            // 提交事务
            Db::commit();
            $save = true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $errorMessage = $e->getMessage();
            $save         = false;
        }

        return json(['code' => ApiStatus::API_SUCCESS->value, 'msg' => $save ? '操作成功' : '操作失败:' . $errorMessage, 'data' => null], JSON_PRESERVE_ZERO_FRACTION | JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
    }
}